package com.psjj.privilege.web.listener;

import com.psjj.privilege.po.Privilege;
import com.psjj.privilege.service.PrivilegeService;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

@WebListener
public class MyServletContextListener implements ServletContextListener {
    private PrivilegeService privilegeService = new PrivilegeService();
    @Override //监听到servletContext对象创建的时候运行，servletContext在服务器启动的时候创建
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //获得servletContext对象
        ServletContext servletContext = servletContextEvent.getServletContext();
        //设置全局的工程名
        setContextPath(servletContext);
        //加载一级菜单数据，并让一级菜单数据关联子菜单数据
        loadTopPrivileges(servletContext);
        //加载所有访问路径urls用于控制三级权限
        loadUrls(servletContext);
        
    }
    //加载所有urls
    private void loadUrls(ServletContext servletContext) {
        List<String> urls = privilegeService.queryUrls();
        servletContext.setAttribute("urls",urls);
    }

    //加载一级菜单数据，并让一级菜单数据关联子菜单数据
    private void loadTopPrivileges(ServletContext servletContext) {
        List<Privilege> list = privilegeService.queryTopPrivileges();
        servletContext.setAttribute("topPrivileges",list);
    }

    //设置全局工程名
    private void setContextPath(ServletContext servletContext) {
        servletContext.setAttribute("path",servletContext.getContextPath());
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
